#!/bin/bash
# exit when any command fails
set -e

# Functions
function help()
{
  cat << EOF >&2
Usage: ${0##*/} [options]

This run script will assist you to run assuremappingtools container

    -h,--help               Show this help
  Optional:
    -b,--branch             Branch name or tag name, if not provided it uses master.
    -w,--workspace          Absolute path for the working directory, if not provided no workspace added
                            This should be used to access your files on the host machine.
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    -h|--help)
      help
      exit 0 ;;
    -b|--branch)
      TAG="$2"
      shift 2 ;;
    -w|--workspace)      
      if [[ "${2:0:1}" = "/" ]]; then
        if [[ -d $2 ]]; then
          WORKSPACE="$2"
        else
          echo "The provided workspace is not exist: $2" >&2
          exit 1
        fi
      else
        echo "The provided workspace path should be absolute" >&2
        exit 1
      fi
      shift 2 ;;
    --)
      shift; break ;;
    *)
      echo "Unknown option: $1" >&2
      exit 1 ;;
  esac
done

if [ -z "$TAG" ]
  then
    echo "No specific tag provided using 'master'"
    TAG=master
else
    echo "tag specified using '${TAG}'"
fi

if [ -z "$WORKSPACE" ]
  then
    echo "No specific workspace path provided. Running without workspace."
else
    echo "using '${WORKSPACE}' as data workspace and added as volume under '/assuremappingtools/Maps'"
    ADD_VOLUME="-v ${WORKSPACE}:/assuremappingtools/Maps"
fi

xhost + && \
docker run -it --rm \
--env="DISPLAY=$DISPLAY" \
${ADD_VOLUME} \
--volume=/tmp/.X11-unix:/tmp/.X11-unix \
--device=/dev/dri/card0:/dev/dri/card0 \
--privileged \
zatitech/assuremappingtools:${TAG}